"""
做权限的初始化，获取当前用户哦所有的权限，并保存到session
"""
from django.conf import settings


def init_permissions(current_user, request):
    # 获取该用户下的所有权限,去出没有分配角色和用户的权限
    permission_queryset = current_user.roles.filter(permissions__isnull=False).values(
        'permissions__url', 'permissions__id', 'permissions__title',
        'permissions__menu_id','permissions__menu__title','permissions__menu__icon',
        'permissions__pid_id','permissions__pid__title','permissions__pid__url','permissions__alias'
    ).distinct()
    # 获取能作为菜单的权限列表
    # permission_menu_list = []
    # 定义菜单字典
    menu_dic={}
    # 该用户所有的权限列表
    permission_dic = {}
    for item in permission_queryset:
        # 将权限列表添加至session,以别名作为字典的key值
        permission_dic[item['permissions__alias']]={
            'url':item['permissions__url'],
            'title':item['permissions__title'],
            'pid':item['permissions__pid_id'],
            'p_title':item['permissions__pid__title'],
            'p_url':item['permissions__pid__url']
                                }
        menu_id = item['permissions__menu_id']
        if not menu_id:
            continue
        if menu_id in menu_dic:
            menu_dic[menu_id]['children'].append( {'title':item['permissions__title'],'url':item['permissions__url']})
        else:
            menu_dic[menu_id]={
                'title':item['permissions__menu__title'],
                'icon':item['permissions__menu__icon'],
                'children':[
                    {'title':item['permissions__title'],'url':item['permissions__url']}
                ]
            }
    # 将权限存入session
    # permission_list = [item['permissions__url'] for item in permission_queryset]
    request.session[settings.PERMISSION_MENU_SESSION_KEY] = menu_dic
    request.session[settings.PERMISSION_SESSION_KEY] = permission_dic
